package com.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/get")
    public String init(String userName) {
        return userName + ":" + UUID.randomUUID().toString();
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        // 待下载文件名
        String fileName = "种植牙.txt";
        String filePath = "C:\\Users\\admin\\Desktop\\" + fileName;
        // 设置为png格式的文件
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
        IOUtils.copy(new FileInputStream(FileUtils.getFile(filePath)), response.getOutputStream());
    }

    @PostMapping(value = "/post/form", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
    public String postUser(@RequestParam String name, @RequestParam String password) {
        return name + ":" + password;
    }

    @PostMapping(value = "/post/mulit/form", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public Map<String, String> postForm(@RequestParam String name, @RequestParam MultipartFile file) {
        Map<String, String> map = new HashMap<>();
        map.put("name", name);
        map.put("fileName", file.getOriginalFilename());
        return map;
    }

    private static AtomicLong num = new AtomicLong(0);

    @GetMapping("/getId")
    public Long getId() {
        return num.getAndIncrement();
    }

}
